<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">
  <xsl:param name="table_div_id"/>
  <xsl:param name="sortby">2</xsl:param>
  <xsl:param name="prev_sortby"/>
  <xsl:param name="sortorder">ascending</xsl:param>

  <xsl:variable name="new_sortorder">
    <xsl:if test="$prev_sortby=$sortby">
      <xsl:if test="$sortorder='ascending'">descending</xsl:if>
      <xsl:if test="$sortorder='descending'">ascending</xsl:if>
    </xsl:if>
    <xsl:if test="$prev_sortby!=$sortby"><xsl:value-of select="$sortorder"/></xsl:if>
  </xsl:variable>

  <xsl:output method="html"/>
  
  <xsl:template match="/">
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="table">
    <table border="1">
      <tr><xsl:apply-templates mode="head" select="head/data"/></tr>
      <xsl:for-each select="row">
        <xsl:sort select="data[position()=$sortby]" data-type="number" order="{$new_sortorder}"/>
        <tr><xsl:apply-templates mode="row"/></tr>
      </xsl:for-each>
    </table>
  </xsl:template>

  <xsl:template match="data" mode="head">
    <th onmouseover="this.style.cursor='pointer'" onclick="render_table('{$table_div_id}',{{ prev_sortby:{$sortby}, sortby:{position()}, sortorder:'{$new_sortorder}' }})">
      <xsl:if test="position()=$sortby">
        <xsl:attribute name="style">background-color:thistle;</xsl:attribute>
      </xsl:if>
      <xsl:value-of select="."/>
      <xsl:if test="$new_sortorder='ascending' and position()=$sortby"> &#8593;</xsl:if>
      <xsl:if test="$new_sortorder='descending' and position()=$sortby"> &#8595;</xsl:if>
    </th>
  </xsl:template>

  <xsl:template match="data" mode="row">
    <td><span title="{.}"><xsl:value-of select="substring(.,1,50)"/><xsl:if test="string-length(.)&gt;50">...</xsl:if></span></td>
  </xsl:template>

</xsl:stylesheet>
